<?php
/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */
namespace Admin\Model;
use Think\Model\RelationModel;
/**
 * 用户模型
 * @package Admin\Model
 */
class UserModel extends RelationModel {
    protected $tableName = 'users';
    /**
     * 获取指定用户信息
     * @param $uid int 用户UID
     * @param bool $relation 是否关联查询
     * @return mixed 找到返回数组
     */
    public function detail($uid, $relation = true) {
        $user = D('User')->where(array('id' => $uid))->relation($relation)->find();
        return $user;
    }
    /**
     * 改变用户信息
     * @param int $uid
     * @param array $data
     * @return array
     */
    public function update($uid = 0, $data = array()) {
        $db_res = D('User')->where(array("id" => $uid))->data($data)->save();
        if ($db_res) {
            return array(1, "用户信息修改成功");
        } else {
            return array(0, "用户信息修改失败");
        }
    }
    /**
     * 添加用户
     * @param $user
     * @return array
     */
    public function addUser($user) {
        if (M('users')->where("phone='" . $user['phone'] . "'")->count() > 0 && $user['email']) {
            return array('status' => -1, 'msg' => '账号已存在');
        }
        $user['password'] = encrypt($user['password']);
        $user['add_time'] = time();
		$user['random'] = rand(1000,9999);
		$data['add_ip'] = get_client_ip();
        $user_id = M('users')->add($user);
        if (!$user_id) {
            return array('status' => -1, 'msg' => '添加失败');
        } else {
            return array('status' => 1, 'msg' => '添加成功');
        }
    }
    /**
     * 改变用户密码
     * @param $uid
     * @param $oldPassword
     * @param $newPassword
     * @return string
     */
    public function changePassword($uid, $oldPassword, $newPassword) {
        $user = $this->detail($uid);
        if ($user['user_pass'] != encrypt($oldPassword)) {
            return array(0, "原用户密码不正确");
        }
        $data['user_id'] = $uid;
        $data['user_pass'] = encrypt($newPassword);
        if (D('User')->where(array("user_id" => $uid))->data($data)->save()) {
            return array(1, "密码修改成功", U("Admin/login/logout"));
        } else {
            return array(0, "密码修改失败");
        }
    }
    /**
     * 生成新的Hash
     * @param $authInfo
     * @return string
     */
    public function genHash(&$authInfo) {
        $User = D('User');
        $condition['id'] = $authInfo['id'];
        $session_code = encrypt($authInfo['id'] . $authInfo['user_pass'] . time());
        $User->where($condition)->setField('user_session', $session_code);
        return $session_code;
    }
    public function getAuth($role_id) {
        return $role_id;
    }
}
